/**
 * 坐骑指令测试脚本
 * 功能：测试4423和4421指令是否正常工作
 */

const WebSocket = require('ws');

// 测试配置
const CONFIG = {
    server: {
        host: 'localhost',
        port: 3000,
        protocol: 'ws'
    },
    // 直接使用token连接
    token: '4600d9f37888dfade167489cc392c288', // 替换为你的实际token
};

class MountCommandTester {
    constructor() {
        this.ws = null;
        this.currentRequest = null;
    }

    // 发送指令并等待响应
    sendCommandAndWait(command, data = null, timeoutMs = 5000) {
        return new Promise((resolve, reject) => {
            try {
                if (this.currentRequest) {
                    return reject(new Error('上一个请求尚未完成'));
                }

                const payload = data ? { c: command, d: data } : { c: command };
                console.log(`📤 发送指令: ${JSON.stringify(payload)}`);
                this.ws.send(JSON.stringify(payload));

                const timeout = setTimeout(() => {
                    const err = new Error(`等待 ${command} 响应超时`);
                    if (this.currentRequest && this.currentRequest.reject) {
                        this.currentRequest.reject(err);
                    }
                    this.currentRequest = null;
                }, timeoutMs);

                this.currentRequest = { command, resolve, reject, timeout };
            } catch (err) {
                reject(err);
            }
        });
    }

    // 延迟工具方法
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 测试4423指令（获取坐骑列表）
    async test4423() {
        console.log('\n🧪 测试4423指令：获取坐骑列表');
        try {
            const resp = await this.sendCommandAndWait(4423);
            console.log(`📥 收到响应: ${JSON.stringify(resp, null, 2)}`);
            
            if (resp && resp.code === 0 && resp.data && Array.isArray(resp.data)) {
                console.log(`✅ 4423指令测试成功，获取到 ${resp.data.length} 个坐骑`);
                return resp.data;
            } else {
                console.log(`❌ 4423指令测试失败，响应格式错误`);
                return null;
            }
        } catch (error) {
            console.error(`❌ 4423指令测试失败: ${error.message}`);
            return null;
        }
    }

    // 测试4421指令（获取坐骑详情）
    async test4421(mountId) {
        console.log(`\n🧪 测试4421指令：获取坐骑详情，ID: ${mountId}`);
        try {
            const resp = await this.sendCommandAndWait(4421, { id: mountId });
            console.log(`📥 收到响应: ${JSON.stringify(resp, null, 2)}`);
            
            if (resp && resp.code === 0 && resp.data) {
                console.log(`✅ 4421指令测试成功，获取到坐骑详情: ${resp.data.name}`);
                return resp.data;
            } else {
                console.log(`❌ 4421指令测试失败，响应格式错误`);
                return null;
            }
        } catch (error) {
            console.error(`❌ 4421指令测试失败: ${error.message}`);
            return null;
        }
    }

    // 连接WebSocket
    async connect() {
        console.log('🔌 连接WebSocket服务器...');
        
        return new Promise((resolve, reject) => {
            try {
                const wsUrl = `ws://${CONFIG.server.host}:${CONFIG.server.port}/user-service/websocket?t=${CONFIG.token}`;
                this.ws = new WebSocket(wsUrl);

                this.ws.on('open', async () => {
                    console.log('✅ WebSocket连接成功');

                    // 保持连接的基础指令
                    this.ws.send(JSON.stringify({ c: 3 }));
                    this.ws.send(JSON.stringify({ "c": 5, "d": { "roleId": 12933 } }));
                    this.ws.send(JSON.stringify({ c: 100 }));

                    resolve();
                });

                this.ws.on('error', (error) => {
                    console.log('❌ WebSocket连接失败:', error.message);
                    reject(error);
                });

                this.ws.on('close', () => {
                    console.log('🔌 WebSocket连接已关闭');
                });

                this.ws.on('message', (data) => {
                    try {
                        const message = JSON.parse(data);
                        console.log(`📨 收到消息: ${JSON.stringify(message)}`);

                        // 处理4423和4421的响应
                        if ((message.act_id == 4423 || message.act_id == 4421) && this.currentRequest) {
                            clearTimeout(this.currentRequest.timeout);
                            const { resolve } = this.currentRequest;
                            this.currentRequest = null;
                            resolve(message);
                        }
                    } catch (error) {
                        console.error('❌ 消息解析失败:', data);
                    }
                });

            } catch (error) {
                reject(error);
            }
        });
    }

    // 运行完整测试
    async runTests() {
        console.log('🚀 开始坐骑指令测试...\n');

        try {
            // 1. 连接WebSocket
            await this.connect();
            await this.delay(1000);

            // 2. 测试4423指令
            const mountList = await this.test4423();
            await this.delay(1000);

            // 3. 测试4421指令（测试前几个坐骑）
            if (mountList && mountList.length > 0) {
                for (let i = 0; i < Math.min(3, mountList.length); i++) {
                    const mount = mountList[i];
                    if (mount.id) {
                        await this.test4421(mount.id);
                        await this.delay(1000);
                    }
                }
            }

            console.log('\n🎉 坐骑指令测试完成！');

        } catch (error) {
            console.error('\n💥 测试过程中发生错误:', error.message);
        } finally {
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
async function main() {
    console.log('🎯 坐骑指令测试脚本');
    console.log('   功能：测试4423和4421指令是否正常工作\n');

    const tester = new MountCommandTester();
    await tester.runTests();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 测试脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = MountCommandTester;
